package org.sbbs.app.demo.webapp.action;

import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.sbbs.app.demo.model.DemoEntity;
import org.sbbs.app.demo.service.DemoEntityManager;
import org.sbbs.base.webapp.action.BaseJqgridEditAction;

public class DemoEntityEditAction extends BaseJqgridEditAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8963383641780249323L;
	private DemoEntity model;
	private DemoEntityManager demoEntityManager;

	public DemoEntity getModel() {
		return model;
	}

	public void setModel(DemoEntity model) {
		this.model = model;
	}

	public DemoEntityManager getDemoEntityManager() {
		return demoEntityManager;
	}

	public void setDemoEntityManager(DemoEntityManager demoEntityManager) {
		this.demoEntityManager = demoEntityManager;
	}

	public String edit() {
		if (getModelId() != null) {
			this.setModel(this.demoEntityManager.get(Long.parseLong(this
					.getModelId())));
			this.setEditType(EDIT_TYPE_EDIT);
		} else {
			this.setModel(new DemoEntity());
			this.setEditType(EDIT_TYPE_NEW);
		}
		return this.SUCCESS;

	}

	public String save() {
		try {
			HttpServletRequest req = this.getRequest();
			boolean isNew = (this.getEditType() == 1);
			this.getDemoEntityManager().save((DemoEntity) model);
			this
					.setMessage(getText((isNew)
							? "demoEntity.added"
							: "demoEntity.updated",
							"no msg key found,save successed."));
		} catch (Exception e) {
			this
					.setMessage(getText("error.saved", new String[]{e
							.getMessage()}));
			this.setReturnCode(RETURN_STATUS_ERROR);
		}
		return this.SUCCESS;
	}

	public String delete() {
		try {

			StringTokenizer ids = new StringTokenizer(this.getDelIds(), ",");
			while (ids.hasMoreTokens()) {
				Long removeId = Long.parseLong(ids.nextToken());
				log.debug("Delete Customer " + removeId);
				this.getDemoEntityManager().remove(removeId);
			}
			this.setMessage(getText("demoEntity.deleted",
					"no msg key found,delete successed."));
		} catch (Exception e) {
			this.setMessage(getText("error.deleted", new String[]{e
					.getMessage()}));
			this.setReturnCode(RETURN_STATUS_ERROR);
		}
		return this.SUCCESS;
	}

}
